package com.twitter;

import team.stride.R;
import team.stride.utils.UtilsStride;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class TwitterLogin extends Activity
{
	private WebView webView;
	private Button ok_btn;
	private EditText pin_code;
	private Handler mHandler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		View v = LayoutInflater.from(getParent()).inflate(R.layout.twitter_layout, null);
		setContentView(v);
		
		initGUI();
		final ProgressDialog dialog = new ProgressDialog(this.getParent());
		dialog.setMessage("Please wait for Twitter to respond!");
		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				final String authUrl = UtilsStride.initTwitter4j();
				mHandler.post(new Runnable()
				{
					@Override
					public void run()
					{
						webView.loadUrl(authUrl);
						dialog.dismiss();
					}
				});
			}
		}).start();
	}

	private void initGUI()
	{
		pin_code = (EditText) findViewById(R.id.twitter_pin_code);
		ok_btn = (Button) findViewById(R.id.twitter_ok_btn);

		ok_btn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				UtilsStride.connectTwitter(pin_code.getText().toString());
				finish();
			}
		});

		webView = (WebView) findViewById(R.id.twitter_webview);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new NoPopWebViewClient());
	}


	private class NoPopWebViewClient extends WebViewClient
	{
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
			view.loadUrl(url);
			return true;
		}
	}
}
